package com.jwj.config;

import com.jwj.pojo.Account;
import com.jwj.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

//自定义的UserRealm  extends AuthorizingRealm
public class UserRealm extends AuthorizingRealm {
    //授权

    @Autowired
    UserService userService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了=>授权");
        //给用户授权
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //拿到当前登录的这个对象
//        Subject subject = SecurityUtils.getSubject();
//        Account currentAccount = (Account) subject.getPrincipal();//拿到当前用户对象
//        System.out.println(currentAccount);
//        info.addStringPermission("user:login");
        return info;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("执行了=>认证");
        //链接数据库
        UsernamePasswordToken userToken = (UsernamePasswordToken) authenticationToken;
        Account account = userService.loginOne(userToken.getUsername());
        if(account==null){//没有这个
            return null;//抛出异常 UnknownAccountException
        }
        //可以加密： MD5
        return new SimpleAuthenticationInfo(account,account.getPassword(),"");
    }
}
